//
//  ZYTabBar.swift
//  WeiBo
//
//  Created by zhangyu on 16/9/19.
//  Copyright © 2016年 zhangyu. All rights reserved.
//

import UIKit
//定义代理协议
protocol ZYTabBarDelegate:NSObjectProtocol {
    func didSelectedComposeButton()
}
class ZYTabBar: UITabBar {
    //定义闭包
    var  composeButtonClosure: (()->())?
    
    //  定义代理对象
    //  使用weak关键那么协议必须要继承NSObjectProtocol
    weak var zyDelegate: ZYTabBarDelegate?
    
   //懒加载
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted)
        
        button.sizeToFit()
        //  添加点击事件
        button.addTarget(self, action: #selector(composeButtonAction), for: .touchUpInside)
        return button
    }()
    
    override init(frame: CGRect){
        super.init(frame: frame)
        setupUI()
    }
    
    @objc private func composeButtonAction() {
        //执行闭包
        composeButtonClosure?()
        
        
        
        //  使用代理对象调用代理方法
        //  ? 表示判断前面的对象是否为nil,如果为nil那么后面的代码就不执行,否则执行后面的代码
        zyDelegate?.didSelectedComposeButton()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        //设置背景图片，防止push的右侧黑色效果
        backgroundImage = UIImage(named: "tabbar_backgroud")
        //添加子控件
        addSubview(composeButton)
    }
    //设置子控件位置
    override func layoutSubviews() {
        //设置编写按钮的中心点
        super.layoutSubviews()
        composeButton.centerX = width / 2
        composeButton.centerY = height / 2
        
        let itemwidth = frame.size.width / 5
        
        var index = 0
        
        for value in subviews{
            if value.isKind(of: NSClassFromString("UITabBarButton")!) {
                value.width = itemwidth
                value.x = CGFloat(index) * itemwidth
                index += 1
                if index == 2{
                    index += 1
                }
            }
        }
        
        
    }
}
